package com.by.yz.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;

import com.android.volley.toolbox.NetworkImageView;
import com.bumptech.glide.Glide;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.chatuidemo.Constant;
import com.by.yz.chatuidemo.DemoHelper;
import com.by.yz.chatuidemo.ui.*;
import com.by.yz.custom.CircleNetworkImageView;
import com.by.yz.entity.Account;
import com.by.yz.entity.UserTest;
import com.by.yz.fragment.vehicleCommunityFragment;
import com.by.yz.fragment.personalCenterFragment;
import com.by.yz.fragment.vehicleDiagnosisFragment;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.UserRESTFul;
import com.by.yz.util.ToJSonObject;
import com.by.yz.welcome.FirstWelcomeActivity;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.util.EMLog;

import org.json.JSONException;
import org.json.JSONObject;

import com.by.yz.chatuidemo.db.InviteMessgeDao;

import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private App application;

    // 三个底部菜单tab布局
    private RelativeLayout knowLayout, iWantKnowLayout, meLayout;
    // 底部菜单图片
    private ImageView knowImg, iWantKnowImg, meImg;
    // 底部菜单的文本
    private TextView knowTv, iWantKnowTv, meTv;
    // 底部菜单切换的Fragment
    private Fragment knowFragment, iWantKnowFragment, meFragment, currentFragment;

    private TextView loginName;
    private CircleNetworkImageView avatar;
    Account account;
    UserTest userTest;

    static Activity mainActivity;
    private long exitTime = 0;
    private android.app.AlertDialog.Builder exceptionBuilder;
    private boolean isExceptionDialogShow = false;
    public boolean isConflict = false;
    public Toast toast;
    private TextView unreadAddressLable;
    private TextView unreadLabel;
    private InviteMessgeDao inviteMessgeDao;
    public boolean isConflict2 = false;
    // user account was removed
    private boolean isCurrentAccountRemoved = false;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("调用onCreate()", "MainonCreate");
        mainActivity = this;
        super.onCreate(savedInstanceState);
        application = (App) getApplication();
        application.addActivity(this);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();//初始化状态

        showExceptionDialogFromIntent(getIntent());

        //设置导航栏NavigationView的点击事件
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View headerView = navigationView.getHeaderView(0);
        loginName = (TextView) headerView.findViewById(R.id.userName);
        avatar = (CircleNetworkImageView) headerView.findViewById(R.id.avatar);
        avatar.setDefaultImageResId(R.mipmap.login_logo);
        avatar.setErrorImageResId(R.mipmap.login_error);
//        avatar.setImageUrl("http://img2.hao661.com/uploads/allimg/c150515/1431E91Z5M10-2194c1.jpg", App.imageLoader);

        initUI();
        initTab();
    }

    @Override
    public void onResume() {
        Log.e("调用onResume()", "MainonResume");
        super.onResume();
        updateUnreadAddressLable();
        updateUnreadLabel();
        AccountRESTFul accountRESTFul = new AccountRESTFul();
        accountRESTFul.get(new AccountRESTFul.IhttpCb() {
            @Override
            public void ok(JSONObject response) {
                JSONObject jsonObject = response;
                account = ToJSonObject.jsonToBean(jsonObject.toString(), Account.class);
                Log.e("当前登录名", account.getLogin());
                if (account.getLogin().equals("anonymoususer")) {
                    Log.e("警告", "危险权限变更，应用即将重启");
                    Intent intent = new Intent(application.getApplicationContext(), FirstWelcomeActivity.class);
                    startActivity(intent);
                    application.finishActivity();

//                    Handler handler = new Handler();
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            Intent intent = new Intent(application.getApplicationContext(), FirstWelcomeActivity.class);
//                            PendingIntent restartIntent = PendingIntent.getActivity(
//                                    application.getApplicationContext(), 0, intent,
//                                    Intent.FLAG_ACTIVITY_NEW_TASK);
//                            AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
//                            mgr.set(AlarmManager.RTC, System.currentTimeMillis(),
//                                    restartIntent); // 立即重启应用
//                            application.finishActivity();
//                        }
//                    }, 2000);//3秒后执行Runnable中的run方法
                }else {
                    UserRESTFul userRESTFul = new UserRESTFul();
                    userRESTFul.getUser(account.getLogin(), new UserRESTFul.UserPOSTCallBack() {
                        @Override
                        public void ok(JSONObject response) throws JSONException {
                            userTest = ToJSonObject.jsonToBean(response.toString(), UserTest.class);
                            loginName.setText(userTest.getnickName());
                            if (userTest.getHeadimg() != null) {
                                avatar.setImageUrl(userTest.getHeadimg(), App.imageLoader);
                            }
                        }

                        @Override
                        public void error(String response) {
                            Log.e("PCF-user-error", "获取用户表失败" + response);
                        }
                    });
                }
            }

            @Override
            public void error(String error) {
                Log.e("hj", error);
            }
        });
        registerBroadcastReceiver();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    /**
     * 初始化底部标签
     */
    private void initTab() {
        Log.e("调用initTab()", "MaininitTab");
        knowLayout = (RelativeLayout) findViewById(R.id.rl_vehicleDiagnosis);
        iWantKnowLayout = (RelativeLayout) findViewById(R.id.rl_vehicleCommunity);
        meLayout = (RelativeLayout) findViewById(R.id.rl_me);
        knowLayout.setOnClickListener(this);
        iWantKnowLayout.setOnClickListener(this);
        meLayout.setOnClickListener(this);

        knowImg = (ImageView) findViewById(R.id.iv_vehicleDiagnosis);
        iWantKnowImg = (ImageView) findViewById(R.id.iv_i_vehicleCommunity);
        meImg = (ImageView) findViewById(R.id.iv_me);
        knowTv = (TextView) findViewById(R.id.tv_vehicleDiagnosis);
        iWantKnowTv = (TextView) findViewById(R.id.tv_i_vehicleCommunity);
        meTv = (TextView) findViewById(R.id.tv_me);
        unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
        unreadAddressLable = (TextView) findViewById(R.id.unread_address_number);
        inviteMessgeDao = new InviteMessgeDao(this);

        // 初始化底部菜单图片资源
        knowImg.setImageResource(R.mipmap.icon_medicineinfo_press);
        knowTv.setTextColor(getResources().getColor(R.color.green_btn_bg));
        iWantKnowImg.setImageResource(R.mipmap.icon_chinadedicommu_normal);
        iWantKnowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
        meImg.setImageResource(R.mipmap.icon_personcenter_normal);
        meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        //intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
                updateUnreadAddressLable();
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * update unread message count
     */
    public void updateUnreadLabel() {
        Log.e("调用updateUnreadLabel()", "更新未读信息");
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            if (count > 99) {
                unreadLabel.setText(99 + "+");
            } else {
                unreadLabel.setText(String.valueOf(count));
            }
            unreadLabel.setVisibility(View.VISIBLE);
        } else {
            unreadLabel.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * update the total unread count
     */
    public void updateUnreadAddressLable() {
//        Log.e("调用updateUnreadAddressLable()", "更新未读请求");
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
                    unreadAddressLable.setVisibility(View.VISIBLE);
                } else {
                    unreadAddressLable.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    /**
     * get unread message count
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    /**
     * get unread event notification count, including application, accepted, etc
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
        return unreadAddressCountTotal;
    }

    /**
     * 初始化fragment
     **/
    private void initUI() {
        Log.e("调用initUI()", "MaininitUI");
        if (knowFragment == null) {
            knowFragment = new vehicleDiagnosisFragment();
        }

        if (!knowFragment.isAdded()) {
            // 提交事务
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.content_layout, knowFragment).commit();

            //记录当前Fragment
            currentFragment = knowFragment;
        }
    }

    // 再按一次退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("调用onKeyDown()", "MainonKeyDown");
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                toast = Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0);
                toast.show();
                exitTime = System.currentTimeMillis();
            } else {
                if (toast != null) {
                    Log.e("关闭toast", "关闭toast");
                    toast.cancel();
                } else {
                    Log.e("toast null", "toast null");
                }
                finish();
                Log.e("退出程序", "退出程序");
//                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化底部菜单事件监听
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_vehicleDiagnosis: // 知道
                clickTab1Layout();
                break;
            case R.id.rl_vehicleCommunity: // 我想知道
                clickTab2Layout();
                break;
            case R.id.rl_me: // 我的
                clickTab3Layout();
                break;
            default:
                break;
        }
    }

    private int getExceptionMessageId(String exceptionType) {
        if (exceptionType.equals(Constant.ACCOUNT_CONFLICT)) {
            return R.string.connect_conflict;
        } else if (exceptionType.equals(Constant.ACCOUNT_REMOVED)) {
            return R.string.em_user_remove;
        } else if (exceptionType.equals(Constant.ACCOUNT_FORBIDDEN)) {
            return R.string.user_forbidden;
        }
        return R.string.Network_error;
    }

    private void showExceptionDialog(String exceptionType) {
        isExceptionDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!com.by.yz.activity.MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (exceptionBuilder == null)
                    exceptionBuilder = new android.app.AlertDialog.Builder(com.by.yz.activity.MainActivity.this);
                exceptionBuilder.setTitle(st);
                exceptionBuilder.setMessage(getExceptionMessageId(exceptionType));
                exceptionBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        App.clearCacheUserToken(MainActivity.this);
                        dialog.dismiss();
                        exceptionBuilder = null;
                        isExceptionDialogShow = false;
                        finish();
                        Intent intent = new Intent(com.by.yz.activity.MainActivity.this, com.by.yz.activity.LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                exceptionBuilder.setCancelable(false);
                exceptionBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e("ywx", "---------color conflictBuilder error" + e.getMessage());
            }
        }
    }

    private void showExceptionDialogFromIntent(Intent intent) {
        EMLog.e("ywx", "showExceptionDialogFromIntent");
        if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)) {
            showExceptionDialog(Constant.ACCOUNT_CONFLICT);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false)) {
            showExceptionDialog(Constant.ACCOUNT_REMOVED);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(Constant.ACCOUNT_FORBIDDEN, false)) {
            showExceptionDialog(Constant.ACCOUNT_FORBIDDEN);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showExceptionDialogFromIntent(intent);
    }

    /**
     * 点击第一个tab
     */
    private void clickTab1Layout() {
        if (knowFragment == null) {
            knowFragment = new vehicleDiagnosisFragment();
        }
        addOrShowFragment(getSupportFragmentManager().beginTransaction(), knowFragment);

        // 设置底部tab变化
        knowImg.setImageResource(R.mipmap.icon_medicineinfo_press);
        knowTv.setTextColor(getResources().getColor(R.color.green_btn_bg));
        iWantKnowImg.setImageResource(R.mipmap.icon_chinadedicommu_normal);
        iWantKnowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
        meImg.setImageResource(R.mipmap.icon_personcenter_normal);
        meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
    }

    /**
     * 点击第二个tab
     */
    private void clickTab2Layout() {
        if (iWantKnowFragment == null) {
            iWantKnowFragment = new vehicleCommunityFragment();
        }
        addOrShowFragment(getSupportFragmentManager().beginTransaction(), iWantKnowFragment);

        knowImg.setImageResource(R.mipmap.icon_medicineinfo_normal);
        knowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
        iWantKnowImg.setImageResource(R.mipmap.icon_chinadedicommu_press);
        iWantKnowTv.setTextColor(getResources().getColor(R.color.green_btn_bg));
        meImg.setImageResource(R.mipmap.icon_personcenter_normal);
        meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));

    }

    /**
     * 点击第三个tab
     */
    private void clickTab3Layout() {
        if (meFragment == null) {
            meFragment = new personalCenterFragment();
        }

        addOrShowFragment(getSupportFragmentManager().beginTransaction(), meFragment);
        knowImg.setImageResource(R.mipmap.icon_medicineinfo_normal);
        knowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
        iWantKnowImg.setImageResource(R.mipmap.icon_chinadedicommu_normal);
        iWantKnowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
        meImg.setImageResource(R.mipmap.icon_personcenter_press);
        meTv.setTextColor(getResources().getColor(R.color.green_btn_bg));

    }

    /**
     * 添加或者显示碎片
     *
     * @param transaction
     * @param fragment
     */
    private void addOrShowFragment(FragmentTransaction transaction,
                                   Fragment fragment) {
        if (currentFragment == fragment)
            return;

        if (!fragment.isAdded()) { // 如果当前fragment未被添加，则添加到Fragment管理器中
            transaction.hide(currentFragment)
                    .add(R.id.content_layout, fragment).commit();
        } else {
            transaction.hide(currentFragment).show(fragment).commit();
        }

        currentFragment = fragment;
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /**
         * 此方法用于初始化菜单，其中menu参数就是即将要显示的Menu实例。 返回true则显示该menu,false 则不显示;
         * (只会在第一次初始化菜单时调用)
         */
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_my_problem) {
            Intent intent = new Intent(MainActivity.this, QuikListActivity.class);
            intent.putExtra("isDoctor", userTest.getflag());
            intent.putExtra("username", EMClient.getInstance().getCurrentUser());
            startActivity(intent);
        } else if (id == R.id.nav_my_msg) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().onNewMsg(message);
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> list) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                Log.e("调用refreshUIWithMessage", "刷新ui信息");
            }
        });
    }
}
